<template>
    <div class="view-container" style="min-width:1266px;">
        <div class="goodsList">
            <div class="role-tab" v-if="!isEdit">
                <el-tag v-for="tag in tags"
                        :key="tag.name"
                        :closable="true"
                        :type="tag.type" v-if="tags.length!==0" @close="handleClose(tag.name)"
                        style="margin: 15px;height: 35px;line-height: 35px;font-size: 14px;">
                    {{tag.name}}
                </el-tag>

                <!--<el-tabs type="card" v-model="goodsStatus" @tab-click="getStatusLists">
                    &lt;!&ndash;点击切换对应的数据&ndash;&gt;
                    <el-tab-pane v-for="item in querytabHeaders" :label="item.label" :name="item.key" :key="item.key">
                        <product-status :state="item.key" v-if="goodsStatus=='上架'" :query-pros="queryPros">

                        </product-status>
                        &lt;!&ndash;第二个 组件&ndash;&gt;
                        <product-status :status="item.key" v-if="goodsStatus=='发布'" @toEdit="editProduct" :isEdit="isEdit"
                                        :query-pros="queryPros">

                        </product-status>
                        &lt;!&ndash;第三个&ndash;&gt;
                        <product-status :status="item.key" v-if="goodsStatus=='提交审核'" :query-pros="queryPros">

                        </product-status>
                        &lt;!&ndash;第四个&ndash;&gt;
                        <product-status :status="item.key" v-if="goodsStatus=='退回'" @toEdit="editProduct" :isEdit="isEdit"
                                        :query-pros="queryPros">

                        </product-status>
                        &lt;!&ndash;分页 渲染数据时候再开始设计&ndash;&gt;

                    </el-tab-pane>
                </el-tabs>-->
                <!--搜索-->

                <el-tabs v-model="goodsStatus" type="card" @tab-click="getStatusLists">
                    <el-tab-pane v-for="tab in querytabHeaders" :key="tab.name" :name="tab.name">
                    <span slot="label">
                        {{tab.label}}
                    </span>

                    </el-tab-pane>
                </el-tabs>

                <div>
                    <keep-alive>
                        <component :is="goodsStatus" :isEdit="isEdit" :query-pros="queryPros" @to-edit="toEdit"
                                   @is-change="isChange" @get-id="sendId" @up-date="update" @edit-type="getPubType">
                        </component>
                    </keep-alive>
                </div>
                <div class="pagination-container" v-if="!queryPros.length==0">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                   current-page.sync="currentPage" :page-sizes="[5,10,15,20]" :page-size="pageSize"
                                   layout="total, sizes, prev, pager, next, jumper" :total="totalSum">
                    </el-pagination>
                </div>

            </div>
            <!--商品编辑模块  传递-->
            <div class="productEdit" v-if="isEdit">
                <div v-if="!pubType && canEdit">
                    <el-tabs v-model="editPro" type="card" @tab-click="tabChange">
                        <el-tab-pane v-for="tab in setproHeaders" :key="tab.key" :name="tab.key">
                    <span slot="label">
                        {{tab.label}}
                    </span>
                        </el-tab-pane>
                    </el-tabs>

                    <div class="">
                        <keep-alive>
                            <component :is="currentComponent" @nextprew="nextprew" :is-edit="isEdit" :info="info" @reset="reset"
                                       @cancel-edit="cancleEdit" @edit-success="editSuccess" ref="component">
                            </component>
                        </keep-alive>
                    </div>
                    <div style="display: block; text-align: center;margin-top: 24px;">
                        <el-button @click="cancelEdit">取消编辑</el-button>
                    </div>
                </div>

                <div v-if="pubType && canEdit">
                    <el-tabs type="card" v-model="editProFast">
                        <el-tab-pane label="具体信息" name="info">
                            <!--第一个基本信息组件-->
                            <fast-pro-info :is-edit="isEdit" :info="info" @reset="reset" @cancel-edit="cancleEdit">
                            </fast-pro-info>
                        </el-tab-pane>
                    </el-tabs>
                    <div style="display: block; text-align: center;margin-top: 24px;margin-left: 38px;">
                        <el-button @click="cancelEdit">取消编辑</el-button>
                    </div>

                </div>
            </div>
        </div>
    </div>

</template>

<script>
    import productFilter from './tabcontent/components/product_filter.vue';
    import proInfo from './tabcontent/proInfo.vue';
    import proIntro from './tabcontent/proIntro.vue';
    import proParams from './tabcontent/proParams.vue';
    import proSpeci from './tabcontent/proSpeci.vue';
    import {getGoodsList} from '@/api/goods';
    import {parseTime, formatTime} from '@/utils/datetime';
    import {getFirCategory} from '@/api/category'
    import productStatusPutAway from './tabcontent/product_status_put_away.vue'
    import productStatusInStorage from './tabcontent/product_status_in_storage.vue';
    import productStatusCheckFailure from './tabcontent/product_status_check_failure.vue'
    import productStatusCheckPending from './tabcontent/product_status_check_pending.vue';
    import {getDetail, getCheckByWeek} from '@/api/goods';
    import {clearSession} from '@/utils/removeSession';
    import fastProInfo from './tabcontent/fastproinfo.vue';
    import {getTab, setTab} from '@/utils/list';
    import { getProInfo} from '@/utils/storeProInfo';
    // 数据直接渲染  tags
    //  CHECK_FAILURE-审核失败（回收站）,  退回
    //  CHECK_PENDING-待审核,            提交审核
    //  IN_STORAGE-仓库中（下架）,         发布
    //  PUTAWAY-上架                     上架
    export default {
        components: {
            'pro-info': proInfo,
            'pro-intro': proIntro,
            'pro-params': proParams,
            'pro-speci': proSpeci,
            'product-status-check-pending': productStatusCheckPending,
            'product-status-put-away': productStatusPutAway,
            'product-status-in-storage': productStatusInStorage,
            "product-status-check-failure": productStatusCheckFailure,
            'product-filter': productFilter,
            'fast-pro-info': fastProInfo,
        },
        name: 'goodsList',
        data() {
            return {
                editProFast: 'info',
                canEdit: false,
                isShow1: true,
                isShow2: true,
                info: {},
                pageSize: 5,
                currentPage: 1,
                totalSum: 0,
                category: [],
//          总条数
                listLoading: true,
                isEdit: false,
                tags: [],
                goodsStatus: 'product-status-put-away',
                querytabHeaders: [
                    {label: "已上架", key: "PUTAWAY", name: 'product-status-put-away'},
                    {label: "仓库中", key: "IN_STORAGE", name: 'product-status-in-storage'},
                    {label: "审核中", key: "CHECK_PENDING", name: 'product-status-check-pending'},
                    {label: "回收站", key: "CHECK_FAILURE", name: 'product-status-check-failure'}
                ],
                editPro: 'pro-info',
                currentComponent:'pro-info', //当前tab内容组件
                setproHeaders: [
                    {label: "基本信息", key: "pro-info"},
                    {label: "商品介绍", key: "pro-intro"},
                    {label: "商品参数", key: "pro-params"},
                    {label: "规格类型", key: "pro-speci"}
                ],
                queryPros: [],
                passNum: 0,
                notPassNum: 0,
                pubType: false,
                tmp: false
            }
        },
        mounted() {
            sessionStorage.removeItem('QUERY_PARAMS');
            this.getNums();
            let activetab = getTab();
//            console.log(activetab);
            if (this.querytabHeaders.some((tab) => {
                    return activetab === tab.name
                })) {
                this.goodsStatus = activetab;
                sessionStorage.removeItem('QUERY_PARAMS');
            }
//      只传一个状态的时候
            this.pageSize = 5;
            this.currentPage = 1;
            let data = {};
            this.uniGetData(data);

//        只有查询参数提交才会触发getFilterDate

            this.$root.eventHub.$on('get-filter-date', (resp) => {
                this.queryPros = resp.data.list;
                this.totalSum=resp.data.total;
            });
        },
        methods: {
            getPubType(val) {
//                获取发布类型 默认是非标品
//                console.log(val);
                this.pubType = val;
            },
            update(arr) {
                let i;
                for (i = this.queryPros.length-1; i >=0; i--) {
                    let item = this.queryPros[i];
                    for(let item1 of arr){
                        if (item1 == item.id) {
                            this.queryPros.splice(i, 1);

                        }
                    }
                }
            },
            close(tag) {
//                console.log(tag);
            },
            getData(data) {
                let params = {pageSize: this.pageSize, pageNum: this.currentPage,desc:true};
                getGoodsList(Object.assign({}, data, params))
                    .then((resp) => {
//                        console.log(resp);
                        this.queryPros = resp.data.list;
//                        this.formatT(str);
                        this.totalSum = resp.data.total;

                    }).catch((err) => {
//                    console.log(err);
                });
            },
            /*,
            formatT(str) {
                for (let item of this.queryPros) {
//                    console.log(item);
                    item[str] = item[str] ? parseTime(item[str]) : ''
                }
            },*/
            getStatusLists(tab, event) {
//
//                this.$root.eventHub.$emit("sendStatus", this.goodsStatus);
//           console.log(typeof tab.index);
//                console.log(tab, event);
//                console.log(tab.name);
                if (tab) {
                    setTab(tab.name);
                }
                this.pageSize=5;
                this.currentPage=1;
                this.goodsStatus = getTab();
//                console.log(this.goodsStatus);
                let data = {};
                this.uniGetData(data);
            },
            editProduct(value) {
//                console.log(value);
                this.isEdit = value;
            },
            handleSizeChange(val) {
//          输入页数后触发
                this.pageSize = val;
                let data = {};
                let queryparams={};
                if(sessionStorage.getItem('QUERY_PARAMS')){
                    queryparams=JSON.parse(sessionStorage.getItem('QUERY_PARAMS'));
                }
                this.uniGetData(Object.assign({},data,queryparams));
            },
            handleCurrentChange(val) {
//点击当前需要显示的页数的时候改变
                this.currentPage = val;
                let data = {};
                let queryparams={};
                if(sessionStorage.getItem('QUERY_PARAMS')){
                    queryparams=JSON.parse(sessionStorage.getItem('QUERY_PARAMS'));
                }
                this.uniGetData(Object.assign({},data,queryparams));
            },
            uniGetData(data){
                if (this.goodsStatus == 'product-status-in-storage'){
                    data = {status: 'IN_STORAGE',orderBy:'check_finish_time'};
                    this.getData(data)
                } else if (this.goodsStatus == 'product-status-check-pending') {
                    data = {status: 'CHECK_PENDING',orderBy:'check_submit_time'};
                    this.getData(data)
                } else if (this.goodsStatus == 'product-status-check-failure') {
                    data = {status: 'CHECK_RECYCLE',orderBy:'return_time'};
                    this.getData(data);
                } else {
                    data = {status: 'PUTAWAY',orderBy:'putaway_time'};
                    this.getData(data);
                }
            },
            tabChange(tab, event) {
                if(tab.name){
                   // console.log(JSON.stringify(getProInfo()));
                    //console.log('current component:' + this.currentComponent);
                    //console.log('target component:' + tab.name);
                    this.$refs['component'].save();
                    setTimeout(()=>{
                        this.currentComponent = tab.name;
                    },50);
                }
            },
            toEdit(val) {
                this.isEdit = val;
            },
            nextprew(val) {
                this.currentComponent = val;
                this.editPro=val;
            },
            isChange() {
                this.getStatusLists();
            },
            sendId(id) {
//                console.log(id);
                if (id) {
                    let data = {
                        id: id
                    };
                    getDetail(data)
                        .then((resp) => {
//                            console.log(resp);
                            this.info = resp.data;
                            this.canEdit = true;
                        })
                        .catch((err) => {
//                            console.log(err)
                        })
                }
            },
            cancleEdit(val) {
//                触发的事件
                this.isEdit = false;
//                清楚本地缓存
                clearSession();
                this.goodsStatus=getTab();
//                this.info={};
                this.getStatusLists();
            },
            reset(val) {

            },
            getNums() {
                getCheckByWeek()
                    .then((resp) => {
//                        console.log(resp);
                        if (resp.data.passCheck != 0) {
                            this.tags.push({
                                name: '本周您有' + resp.data.passCheck + '个商品通过审核，快去仓库中设置库存并上架吧！', type: 'success'
                            });
                        }
                        if (resp.data.notPassCheck != 0) {
                            this.tags.push({
                                name: '本周您有' + resp.data.notPassCheck + '个商品未通过审核，请进入回收站根据提示修改后提交审核！', type: 'danger'
                            })
                        }

                    }).catch((err) => {
//                    console.log(err)
                });
            },
            handleClose(name) {
//                console.log(this.tags);
                for (let i = 0; i < this.tags.length; i++) {
                    if (this.tags[i].name == name) {
                        this.tags.splice(i, 1);
                    }
                }

            },
            cancelEdit() {
//                取消编辑
                this.$confirm('您要编辑的商品信息将会丢失, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$router.push({name: 'goodsList'});
                    this.canEdit = false;
                    this.isEdit = false;
                    this.currentComponent = 'pro-info';
                    this.editPro='pro-info';
                    this.goodsStatus = getTab();
                    clearSession();
                }).catch(() => {

                });
            },
            editSuccess(){
                this.canEdit = false;
                this.isEdit = false;
                this.currentComponent = 'pro-info';
                this.editPro='pro-info';
                this.goodsStatus = getTab();
                clearSession();
                this.getStatusLists();
            }
        },

    }
</script>

<style lang="less" scoped>
    .goodsList {
        .editBtn {
            text-align: center;
            margin-top: 24px;
            .el-button {
                margin-left: 40px;
            }
        }
        .pagination-container {
            margin-top: 24px;
            text-align: center;
        }
    }

</style>
